/*
 * Copyright 2008. Mount Sinai Hospital, Toronto, Canada.
 * 
 * Licensed under the Apache License, Version 2.0. You
 * can find a copy of the license at:
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * IN NO EVENT SHALL MOUNT SINAI HOSPITAL BE LIABLE TO ANY PARTY FOR DIRECT, 
 * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST 
 * PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, 
 * EVEN IF MOUNT SINAI HOSPITAL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
 * DAMAGE.
 * 
 * MOUNT SINAI HOSPITAL SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND 
 * ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". 
 * MOUNT SINAI HOSPITAL HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, 
 * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 
 */

package com.sinai.mshab.extensions.search;

import java.util.ArrayList;

import com.google.gwt.user.client.ui.ListBox;
import com.sinai.mshab.format.util.Observable;
import com.sinai.mshab.format.util.Observer;

/**
 * A dropdown list allowing the user to select by which fields to sort their
 * results by in {@link AdvancedSearch}
 * 
 * @author serge
 * 
 */
public class SortByWidget extends ListBox implements Observer {

	private static SortByWidget instance;
	private ArrayList alreadyIn = new ArrayList();

	private SortByWidget() {

	}

	/**
	 * Retreives the instance of the sort by widget.
	 * 
	 * @return
	 */
	public static SortByWidget getInstance() {
		if (instance == null) {
			instance = new SortByWidget();
		}
		return instance;
	}

	/**
	 * This method is called by observers, namely {@link SearchField}s to
	 * notify this list of their existance
	 */
	public void update(Observable o, Object arg) {
		if (o instanceof SearchField) {
			SearchField field = (SearchField) o;
			String state = (String) arg;

			String table = field.getTableName();
			String name = field.getField();
			String composite = name + " (" + table + ")";

			// add anything new
			if (state.equals(SearchField.CREATED_STATE)) {

				// do not add the same thin several times
				if (!alreadyIn.contains(composite)) {
					alreadyIn.add(composite);
					addItem(composite);
				}
			}
		}
	}
}
